package com.yf.modules.customer.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.boot.base.api.api.dto.PagingReqDTO;
import com.yf.boot.base.api.utils.BeanMapper;
import com.yf.modules.customer.dto.CsContactDTO;
import com.yf.modules.customer.entity.CsContact;
import com.yf.modules.customer.enums.DynamicType;
import com.yf.modules.customer.mapper.CsContactMapper;
import com.yf.modules.customer.service.CsContactService;
import com.yf.modules.customer.service.CsCustomerService;
import com.yf.modules.customer.service.CsDynamicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 联系记录业务实现类
 * </p>
 *
 * @author 聪明笨狗
 * @since 2021-07-07 12:01
 */
@Service
public class CsContactServiceImpl extends ServiceImpl<CsContactMapper, CsContact> implements CsContactService {

    @Autowired
    private CsCustomerService customerService;

    @Autowired
    private CsDynamicService dynamicService;

    @Override
    public IPage<CsContactDTO> paging(PagingReqDTO<CsContactDTO> reqDTO) {

        // 创建分页对象
        Page query = new Page(reqDTO.getCurrent(), reqDTO.getSize());


        //查询条件
        QueryWrapper<CsContact> wrapper = new QueryWrapper<>();

        // 请求参数
        CsContactDTO params = reqDTO.getParams();

        // 倒序排列
        wrapper.lambda()
                .eq(CsContact::getCustomerId, params.getCustomerId())
                .orderByDesc(CsContact::getCreateTime);

        //获得数据
        IPage<CsContact> page = this.page(query, wrapper);
        //转换结果
        IPage<CsContactDTO> pageData = JSON.parseObject(JSON.toJSONString(page),
                new TypeReference<Page<CsContactDTO>>() {
        });
        return pageData;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(CsContactDTO reqDTO) {

        //复制参数
        CsContact entity = new CsContact();
        BeanMapper.copy(reqDTO, entity);
        this.saveOrUpdate(entity);

        // 更新联系时间
        customerService.updateContact(reqDTO.getCustomerId(), "");

        // 记录动态
        dynamicService.save(reqDTO.getCustomerId(), "联系了客户："+reqDTO.getRemark(), DynamicType.CONTACT,
                reqDTO.getResult().equals(3)?1:3);

    }
}
